package cn.xuchunh.campusbbs.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewCompat;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.facebook.drawee.view.SimpleDraweeView;

import org.json.JSONException;
import org.json.JSONObject;

import cn.xuchunh.campusbbs.AppContext;
import cn.xuchunh.campusbbs.R;
import cn.xuchunh.campusbbs.base.BaseActivity;
import cn.xuchunh.campusbbs.bean.User;
import cn.xuchunh.campusbbs.net.HttpRequestManager;
import cn.xuchunh.campusbbs.net.SimpleXJsonListener;
import cn.xuchunh.campusbbs.ui.fragments.UserFragment;
import cn.xuchunh.campusbbs.utils.AppUtil;
import cn.xuchunh.campusbbs.utils.IntentParamsKey;
import cn.xuchunh.campusbbs.utils.JsonKey;
import cn.xuchunh.campusbbs.utils.JsonParser;

/**
 * Created by XuChunH on 2015/10/19.
 */
public class UserActivity extends BaseActivity {

    private TextView title;
    private SimpleDraweeView avatar;
    private UserFragment userFragment;
    private User user;
    private boolean inited;

    public static void launch(Context context, int userId) {
        Intent intent = new Intent(context, UserActivity.class);
        intent.putExtra(IntentParamsKey.USER_ID, userId);
        context.startActivity(intent);
    }


    @Override
    protected void beforeInitView() {
        setShowHomeUp(true);
        int userId = getIntent().getIntExtra(IntentParamsKey.USER_ID, getUser().getUserId());
        if (userId != getUser().getUserId()) {
            user = new User();
            user.setUserId(userId);
        } else {
            user = getUser();
        }
    }

    @Override
    protected void initView(View view) {
        setTitle("");
        title = (TextView) findViewById(R.id.title);
        avatar = ((SimpleDraweeView) findViewById(R.id.avatar));
        ViewCompat.setAlpha(title, 0);
        ViewCompat.setAlpha(avatar, 1);
        findViewById(R.id.user_info_background).setBackgroundDrawable(AppUtil.getMaterialBanner(this));

        if (user.getUserId() == getUser().getUserId() && !TextUtils.isEmpty(getUser().getUserTitle())) {
            showUserInfo();
        } else {
            loadUserInfoFromServer();
        }


    }

    @Override
    protected int createContentRes() {
        return R.layout.activity_user;
    }

    @Override
    protected void onDestroy() {
        inited = false;
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if(user.getUserId() == getUser().getUserId() || !inited){
            return super.onCreateOptionsMenu(menu);
        }
        getMenuInflater().inflate(R.menu.menu_user, menu);
        if(user.isFollow()){
            menu.findItem(R.id.menu_follow).setTitle("取消关注");
        }
        if(user.isFriend()){
            menu.findItem(R.id.menu_friend).setTitle("删除好友");
        }
        return true;
    }

    private void showUserInfo() {
        userFragment = UserFragment.newInstance(user);
        avatar.setImageURI(Uri.parse(user.getAvatar()));
        title.setText(user.getUserName());
        ((TextView) findViewById(R.id.username)).setText(user.getUserName());
        ((TextView) findViewById(R.id.usertitle)).setText(user.getUserTitle());
        ((TextView) findViewById(R.id.email)).setText(user.getEmail());
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.container, userFragment, UserFragment.class.getSimpleName());
        ft.commit();
        ((AppBarLayout) findViewById(R.id.app_bar)).addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                float total = appBarLayout.getTotalScrollRange();
                float percent = Math.abs(verticalOffset) / total;
                ViewCompat.setAlpha(title, percent);
                ViewCompat.setAlpha(avatar, 1 - percent);
                if (percent < 0.05f && !userFragment.isRefreshLayoutEnabled()) {
                    userFragment.updateRefreshState(true);
                } else if (percent > 0.05f && userFragment.isRefreshLayoutEnabled()) {
                    userFragment.updateRefreshState(false);
                }
            }
        });

        inited = true;

    }

    private void loadUserInfoFromServer() {
        HttpRequestManager.getInstance(this).loadUserInfo(
                user.getUserId(),
                jsonListener,
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                },
                UserActivity.class.getSimpleName());
    }

    private SimpleXJsonListener<User> jsonListener = new SimpleXJsonListener<User>() {
        @Override
        public User parseData(JSONObject jsonObject) throws Exception {
            User user = new User();
            user.setFlag(jsonObject.optInt(JsonKey.FLAG));
            user.setBlack(jsonObject.optInt(JsonKey.IS_BLACK) != 0);
            user.setFollow(jsonObject.optInt(JsonKey.IS_FOLLOW) != 0);
            user.setFriend(jsonObject.optInt(JsonKey.ISFRIEND) != 0);
            user.setAvatar(jsonObject.optString(JsonKey.ICON));
            user.setUserName(jsonObject.optString(JsonKey.NAME));
            user.setEmail(jsonObject.optString(JsonKey.EMAIL));
            user.setStatus(jsonObject.optInt(JsonKey.STATUS));
            user.setGender(jsonObject.optInt(JsonKey.GENDER));
            user.setCredits(jsonObject.optInt(JsonKey.CREDITS));
            user.setExtCredits(jsonObject.optInt(JsonKey.GOLD_NUM));
            user.setTopicNum(jsonObject.optInt(JsonKey.TOPIC_NUM));
            user.setPhotoNum(jsonObject.optInt(JsonKey.PHOTO_NUM));
            user.setReplyPostsNum(jsonObject.optInt(JsonKey.REPLY_POSTS_NUM));
            user.setEssenceNum(jsonObject.optInt(JsonKey.ESSENCE_NUM));
            user.setFriendNum(jsonObject.optInt(JsonKey.FRIEND_NUM));
            user.setFollowNum(jsonObject.optInt(JsonKey.FOLLOW_NUM));
            user.setLevel(jsonObject.optInt(JsonKey.LEVEL));
            user.setUserTitle(jsonObject.optString(JsonKey.USERTITLE));
            JSONObject body = jsonObject.optJSONObject(JsonKey.BODY);
            user.setProfileList(
                    JsonParser.parseSimpleDataList(
                            body.optJSONArray(JsonKey.PROFILELIST)
                    )
            );
            user.setCreditsList(
                    JsonParser.parseSimpleDataList(
                            body.optJSONArray(JsonKey.CREDITLIST)
                    )
            );
            return user;
        }

        @Override
        public void onResponse(User response) {
            response.setUserId(user.getUserId());
            user = response;
            if (user.getUserId() == getUser().getUserId()) {
                AppContext.getInstance().setUser(user);
            }
            showUserInfo();
            invalidateOptionsMenu();
        }
    };


}
